import Vue from 'vue'
import store from '../store/index.js'
import SmallappModel from '@/models/SmallappModel.js'
import AccountModel from '@/models/AccountModel.js'
import BindModel from '@/models/BindUserModel.js'

class base {

	async login() {
		if (!store.state.token) {
			await this.smallappLogin()
		}
	}

	//小程序登录
	async smallappLogin() {
		uni.login({
			provider: 'weixin',
			success: async res => {
				const info = await SmallappModel.login({
					code: res.code
				})
				console.log('info', info)
				if (info.code == 200) {
					store.commit('changeUserInfo', info.data)
					this.init()
					// this.msg('登录成功')
				} else {
					this.alert('登录失败,请退出重新登录')
				}
			}
		})
	}


	//提示
	alert(msg, callback) {
		uni.showModal({
			title: '提示',
			content: msg,
			showCancel: false,
			success() {
				callback && callback();
			}
		});
		return false;
	}


	//上传图片
	uploadImg(path, sCallback) {
		var url = apiUrl + 'ajax/upload';

		wx.uploadFile({
			url: url,
			filePath: path,
			name: 'file',
			formData: {
				'user': 'test'
			},
			success: function(res) {
				var res = JSON.parse(res.data);
				if (res.code == 200) {
					sCallback && sCallback(res);
				} else {
					that._processError(res);
					that.alert('上传出错' + res.msg);
				}
			}
		})

	}

	msg(msg) {
		uni.showToast({
			title: msg,
			icon: 'none'
		})
	}

	init() {
		//获取用户列表
		BindModel.users().then(res => {
			const user = store.state.userInfo
			const users = []

			users.push({
				id: user.id,
				name: '自己'
			})

			if (res.data) {
				res.data.forEach(item => {
					users.push({
						id: item.user_id,
						name: item.remark
					})
				})
			}

			store.commit('changeUsers', users)
		})

		//获取账户列表
		AccountModel.my().then(res => {
			store.commit('changeAccounts', res.data)
		})

		this.getFundsType()
	}
	
	getFundsType() {
		//获取记账类型
		AccountModel.getFundsType().then(res => {
			store.commit('changeFundTypes', res.data)
		})
	}
}

const Base = new base();

export default Base